package modules

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"io/ioutil"
	"strings"
	"encoding/json"
	"regexp"
)

/// 谷歌翻译
func Taranslate(c *gin.Context) {
	if word, error := c.GetQuery("words"); error {
		cnword := TaranslateCn(word)
		cnword = strings.Replace(cnword, " ","", -1)
		c.String(http.StatusOK, "%s", cnword)
	} else {
		c.String(http.StatusOK, "%s", "")
	}
}

/// 谷歌搜索列表
func FetchSearchList(c *gin.Context) {
	word, error := c.GetQuery("words")
	word = strings.Replace(word, " ", "", -1)
	result := ""
	url    := ""
	if error && word != "" {
		url = amazonSearchUrl+word
		/// 判断该商品jan码是否存在 错误单号队列中
		hasfile, _ := Exists(ErrorJanPath+word+".html")
		if hasfile == false {
			/// 判断是否已经爬取到相关数据
			hashtmlfile, _ := Exists(DownloadJanPath+word+".html")
			if hashtmlfile == false {
				/// 判断jancode还是商品名称 ^\d*$
				/// 正则 \[\[\["(.*?)\"
				digitsRegexp := regexp.MustCompile(`^\d*$`)
				matchStrs := digitsRegexp.FindString(word)
				/// 商品名称搜索模式
				if matchStrs == "" {
					/// 商品名称模式
					if res, status := ParseSearchListHtmlByGoodname(word); status {
						if jsonStr, err := json.Marshal(res); err == nil {
							SaveSearchResult(DownloadJanPath, word, string(jsonStr))
							c.String(http.StatusOK, "%s", string(jsonStr))
						} else {
							c.String(http.StatusOK, "%s", "")
						}
					} else {
						c.String(http.StatusOK, "%s", "")
					}
				} else {
					/// jancode 模式
					if resp, err := http.Get(url); err != nil {
						c.String(http.StatusOK, " %s", "")
					} else {
						defer resp.Body.Close()
						if body, err := ioutil.ReadAll(resp.Body); err != nil {
							c.String(http.StatusOK, " %s", "")
						} else {
							result = string(body)
							if strings.Contains(result, amazonSearchUnfindMsg) {
								/// 保存错误地址
								SaveSearchResult(ErrorJanPath, word, result)
								c.String(http.StatusOK, " %s", "")
							} else {
								/// 解析列表数据
								if res, status := ParaseSearchListHtmlByJancode(word, url); status {
									if jsonStr, err := json.Marshal(res); err == nil {
										SaveSearchResult(DownloadJanPath, word, string(jsonStr))
										c.String(http.StatusOK, "%s", string(jsonStr))
									} else {
										c.String(http.StatusOK, " %s", "")
									}
								} else {
									c.String(http.StatusOK, " %s", "")
								}
							}
						}
					}
				}
			} else {
				/// 已经抓取 直接显示
				if info, err := ioutil.ReadFile(DownloadJanPath+word+".html"); err == nil {
					c.String(http.StatusOK, "%s", string(info))
				} else {
					c.String(http.StatusOK, " %s", "")
				}
			}
		} else {
			c.String(http.StatusOK, " %s", "")
		}
	}
}

/// 谷歌详情页面提取
func FetchGoodDetail(c *gin.Context) {
	word, error := c.GetQuery("words")
	if error {
		c.String(http.StatusOK, "%s", word)
	} else {
		c.String(http.StatusOK, "%s", "")
	}
}